<template>
  <el-dialog
    v-model="visible"
    title="添加用户"
    width="500px"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" placeholder="请输入用户名" />
      </el-form-item>
      
      <el-form-item label="账号" prop="account">
        <el-input v-model="form.account" placeholder="请输入账号" />
      </el-form-item>
      
      <el-form-item label="密码" prop="password">
        <el-input
          v-model="form.password"
          type="password"
          placeholder="请输入密码"
          show-password
        />
      </el-form-item>
      
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" placeholder="请输入邮箱" />
      </el-form-item>
      
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" placeholder="请输入手机号" />
      </el-form-item>
      
      <el-form-item label="性别" prop="gender">
        <el-select v-model="form.gender" placeholder="请选择性别" style="width: 100%">
          <el-option label="未知" :value="0" />
          <el-option label="男" :value="1" />
          <el-option label="女" :value="2" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="用户类型" prop="type">
        <el-select v-model="form.type" placeholder="请选择用户类型" style="width: 100%">
          <el-option label="普通用户" value="user" />
          <el-option label="管理员" value="admin" />
        </el-select>
      </el-form-item>
      
      <el-form-item label="状态" prop="status">
        <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
          <el-option label="正常" :value="1" />
          <el-option label="禁用" :value="0" />
        </el-select>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'

export default {
  name: 'AddUserDialog',
  props: {
    modelValue: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:modelValue', 'success'],
  setup(props, { emit }) {
    const visible = ref(false)
    const loading = ref(false)
    const formRef = ref()
    
    const form = reactive({
      username: '',
      account: '',
      password: '',
      email: '',
      phone: '',
      gender: 0,
      type: 'user',
      status: 1
    })
    
    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 2, max: 20, message: '用户名长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
      ]
    }
    
    watch(() => props.modelValue, (newVal) => {
      visible.value = newVal
      if (newVal) {
        resetForm()
      }
    })
    
    watch(visible, (newVal) => {
      emit('update:modelValue', newVal)
    })
    
    const resetForm = () => {
      Object.assign(form, {
        username: '',
        account: '',
        password: '',
        email: '',
        phone: '',
        gender: 0,
        type: 'user',
        status: 1
      })
      if (formRef.value) {
        formRef.value.clearValidate()
      }
    }
    
    const handleClose = () => {
      visible.value = false
    }
    
    const handleSubmit = async () => {
      try {
        await formRef.value.validate()
        loading.value = true
        
        // 调用后端API添加用户
        const response = await fetch('/api/user/add', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(form)
        })
        
        if (response.ok) {
          const result = await response.json()
          if (result.code === 1) {
            ElMessage.success('用户添加成功')
            emit('success')
            handleClose()
          } else {
            ElMessage.error(result.msg || '添加失败')
          }
        } else {
          const errorText = await response.text()
          console.error('HTTP错误:', response.status, errorText)
          ElMessage.error(`网络错误 (${response.status}): ${errorText}`)
        }
      } catch (error) {
        console.error('添加用户失败:', error)
        console.error('错误详情:', {
          message: error.message,
          stack: error.stack,
          response: error.response
        })
        ElMessage.error(`添加失败: ${error.message}`)
      } finally {
        loading.value = false
      }
    }
    
    return {
      visible,
      loading,
      formRef,
      form,
      rules,
      handleClose,
      handleSubmit
    }
  }
}
</script>

<style scoped>
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
